package com.dingyang.learn.handmadespringframework.springframework;

import com.dingyang.learn.handmadespringframework.app.IAService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dingyang
 */
public class AutoProxyCreatorBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {

    // 缓存已经创建好的aop的bean
    private final Map<String, Object> earlyBeanReferences = new ConcurrentHashMap<>();

    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) {
        Object proxy = createProxy(bean);
        earlyBeanReferences.put(beanName, proxy);
        return proxy;
    }

    public Object createProxy(Object bean) {
        if (bean instanceof IAService) {
            JdkDynimcProxy jdkDynimcProxy = new JdkDynimcProxy(bean);
            return jdkDynimcProxy.getProxy();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)  {
        if (!earlyBeanReferences.containsKey(beanName)) {
            return createProxy(bean);
        }
        return earlyBeanReferences.get(beanName);
    }

}
